use crate::{common, tables::log::TbLog};
use actix_web::{get, web, Responder};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Get {
    operate: Option<String>,
    name: Option<String>,
    begin_time: Option<String>,
    end_time: Option<String>,
}

#[get("")]
async fn get(page: web::Query<common::QueryPage>, query: web::Query<Get>) -> impl Responder {
    log::info!("Get: {:?}", query);
    common::ResData::<TbLog>::from_page(TbLog::get_logs(&page, &query).await).resp_json()
}

pub fn routes(cfg: &mut web::ServiceConfig) {
    cfg.service(web::scope("/log").service(get));
}

#[cfg(test)]
pub mod tests {
    use crate::{
        common,
        handlers::log::{self, Get},
        utils::mysql,
    };
    use actix_web::{test, App};
    use serde_json::Value;

    #[actix_web::test]
    async fn test_get_logs() {
        mysql::init_pool().await;

        let app = test::init_service(App::new().configure(log::routes)).await;

        let page = &mut common::QueryPage::default();
        page.page_size = Some(5);
        let page = serde_urlencoded::to_string(page).unwrap();
        let query = &mut Get::default();
        query.begin_time = Some("2023-04-25+09:18:14".into());
        query.end_time = Some("2023-05-06+09:10:40".into());
        let query = serde_urlencoded::to_string(query).unwrap();

        let req = test::TestRequest::get()
            .uri(&("/log?".to_owned() + page.as_str() + "&" + query.as_str()))
            .to_request();

        let resp = test::call_service(&app, req).await;
        let status = resp.status();
        println!("resp status is {:?}", status);
        let resp_body = test::read_body(resp).await;
        let json_value: Value = serde_json::from_slice(&resp_body).unwrap();
        println!("restp body is {}", json_value);
        assert!(status.is_success());
    }
}
